package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult login(AdUserDto adUserDto) {
        //1.检查参数
        if (adUserDto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isBlank(adUserDto.getName()) ||StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空！");
        }
        //2.根据用户名查询用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        //3.判断查询到的用户是否存在
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"查无此人！");
        }
        //4.判断输入密码和数据库中的密码是否一致
        String s = DigestUtils.md5DigestAsHex((adUserDto.getPassword()+ user.getSalt()).getBytes());
        if (!s.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //5.判断用户的状态是否为9
        if (user.getStatus().intValue()!=9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户的状态异常！");
        }
        //6.更新最后的登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //7.生成token返回封装结果
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user,userVO);//属性拷贝
        Map result = new HashMap<>();
          result.put("user",userVO);
          result.put("token",token);
          return ResponseResult.okResult(result);




    }
}
